<template>
  <div>
    <!-- 背景 -->
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <!-- 添加按钮 -->
      <el-button
        type="primary"
        size="default"
        :icon="Plus"
        @click="addTradeMark"
        >添加</el-button
      >

      <!-- 表格 -->
      <el-table
        border
        style ="margin:10px 0px"
        :data="tmObj.records"
        v-loading="loading"
      >
        <el-table-column
          label="序号"
          width="80px"
          align="center"
          type="index"
        ></el-table-column>
        <el-table-column label="品牌名称" prop="tmName"></el-table-column>
        <el-table-column label="品牌LOGO">
          <template  #="{ row, $index }">
            <a :title="row.tmName">
              <img
                :src="row.logoUrl"
                alt=""
                style="width: 100px; height: 60px; border-radius: 10px"
              />
            </a>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #="{ row, $index }">
            <el-button type="warning" size="small" :icon="Edit" @click="updateTrademark(row)"></el-button>
            <el-popconfirm :title="`确定删除${row.tmName}?`" width="250px" :icon="Delete" @confirm="deleteTradeMark(row)">
              <template #reference>
                <el-button type="danger" size="small" :icon="Delete"></el-button>
              </template>
            </el-popconfirm>
            
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <el-pagination
        @current-change="getTradeMarkList"
        @size-change="sizeHandler"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="tmObj.total"
        :page-sizes="[3, 5, 7]"
        layout=" prev, pager, next, jumper,->,sizes,total"
        background
        :pager-count="7"
      >
      </el-pagination>

      <!-- Dialog对话框--弹框 -->
      <!-- v-model:控制对话框显示与隐藏,布尔值
            draggable:可拖拽的
      -->
      <el-dialog v-model="dialogFormVisible" :title="tmParams.id?'修改品牌':'添加品牌'" draggable>
        <el-form style="width: 80%" label-width="100px" :model="tmParams" :rules="rules" ref="formRef">
          <!-- 获取品牌名称的地方 -->
          <el-form-item label="品牌名称" prop="tmName">
            <el-input autocomplete="off" v-model="tmParams.tmName" />
          </el-form-item>
          <!-- 获取品牌logo的地方 -->
          <el-form-item label="品牌LOGO" prop="logoUrl">
            <el-upload
              class="avatar-uploader"
              action="/api/admin/product/fileUpload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if=" tmParams.logoUrl "
                :src=" tmParams.logoUrl "
                class="avatar"
              />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
        <!-- 对话框下方确定取消的按钮 -->
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="addOrUpdate">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
// 引入消息提示组件
import { ElMessage,ElNotification } from "element-plus";
// 引入element使用的数据类型
import type { UploadProps,FormInstance,FormRules } from "element-plus";
// 引入数据类型
import type {
  trademarkResponseData,
  trademark,
} from "@/api/product/trademark/model/trademark";
// 引入请求
import {
  reqTradeMarkList,
  reqAddOrUpdateTradeMark,
  reqDeleteTradeMark
} from "@/api/product/trademark/trademark";
// 引入elrment-plus提供icon图标组件
import {
  ArrowLeft,
  ArrowRight,
  Delete,
  Edit,
  Share,
  Plus,
} from "@element-plus/icons-vue";
import { ref, onMounted, reactive ,nextTick} from "vue";
// 保存分页器当前页码[当前第几页]
let currentPage = ref<number>(1);
// 保存当前页面显示几条数据
let pageSize = ref<number>(3);
// 定义控制loading效果的响应式数据
let loading = ref<boolean>(false);
// 定义控制对话框显示与隐藏的响应式数据
let dialogFormVisible = ref<boolean>(false);
// 存储组件实例
let formRef = ref<FormInstance>();
// 定义收集新增品牌数据,将来发请求会带
let tmParams = reactive<trademark>({
  tmName:"",
  logoUrl:"",
});
// 定义接收服务器返回品牌数据
let tmObj = reactive<trademarkResponseData>({
  total: 0,
  records: [],
});

// 挂载完成需要先获取一此品牌数据
onMounted(() => {
  // 先获取一次品牌数据
  getTradeMarkList(1);
});

// 专门获取品牌数据的函数
// 获取列表数据
// 由于当前函数作为分页器的回调函数:人家底层会注入当前页码
const getTradeMarkList = async (page: number = 1) => {
  // 请求数据之前加载中
  loading.value = true;
  // 整理参数
  currentPage.value = page;
  // 再次发请求
  let result = await reqTradeMarkList(currentPage.value, pageSize.value);
  //  保存服务器传回来的数据
  tmObj.total = result.total; //数据总数
  tmObj.records = result.records; //品牌数据
  //  数据拿到了不再加载了
  loading.value = false;
};

// 右边下拉菜单修改一页展示几条数据的回调
const sizeHandler = (limit: number) => {
  //  整理参数
  pageSize.value = limit;
  // 再次发请求获取列表数据
  getTradeMarkList();
};

// 图片上传成功后的钩子
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  // console.log(response);
  // console.log( uploadFile);
  tmParams.logoUrl = response.data;
};

// 图片上传前的钩子
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  // console.log(rawFile);

  if (
    rawFile.type == "image/png" ||
    rawFile.type == "image/jpeg" ||
    rawFile.type == "image/gif"
  ) {
    if (rawFile.size / 1024 / 1024 <= 14545) {
      ElMessage({
      message: "成功",
      type: "success",
    });
      return true;
    }
  } else {
    ElMessage({
      message: "失败",
      type: "error",
    });
    return false;
  }
};

// 点击确定按钮,携带品牌名称和品牌logo路径发请求
const addOrUpdate = async () => {
  // 触发el-form组件实例validate方法
  // 全部字段进行验证
  formRef.value?.validate(async(success)=>{
    // 如果全部字段校验成功
   if(success){
     // 发请求
 await reqAddOrUpdateTradeMark(tmParams);
  // 对话框隐藏
  dialogFormVisible.value = false;
    // 获取最新的数据列表    判断是否有id,有是修改留在当前页
    getTradeMarkList(tmParams.id?currentPage.value:1);
       // 提交成功或修改成功的提示
       ElMessage({
      message: tmParams.id?"品牌修改成功":"品牌添加成功",
      type: "success",
    });
  }else{
    ElNotification({
    type: "warning",
    message: '请看清规则再添加',
    duration:500
  })
  }
   })
  }

 

// 点击添加按钮的回调
const addTradeMark = ()=>{
  // 显示弹框
  dialogFormVisible.value =true;
  // 清空数据
  tmParams.id = '';
  tmParams.logoUrl= '';
  tmParams.tmName='';

  // nexTick响应式数据发生改变时,获取最新DOM
  nextTick(()=>{
    formRef.value?.resetFields();
  })
}

// 点击修改按钮修改数据
const updateTrademark = (row:trademark) =>{
    // 显示弹框
    dialogFormVisible.value =true
   

      // nexTick响应式数据发生改变时,获取最新DOM
  nextTick(()=>{
    formRef.value?.resetFields();
     // 收集修改已有数据
     tmParams.id = row.id;
    tmParams.logoUrl = row.logoUrl;
    tmParams.tmName = row.tmName
  })

}

// 自定义表单验证
const validatetmName = (rule:any,value:any,next:any) =>{
    if(value.length >=2 && value.length <10){
      next();
    }else{
      next(new Error('品牌名字大于等于2,小于10'))
    }
}

// 表单验证
const rules = reactive<FormRules>({
    tmName:[
      // {required: true, message: '请不要输入空字符串', trigger: 'blur'},
      // { min: 2, max: 10, message: '请输入2-10个字符串', trigger: 'change' },
      {required: true, trigger: 'blur',validator: validatetmName,}
    ],
    logoUrl:[
      {required: true, message: '请上传图片'},
    ]
})


// 删除确定按钮的回调
const deleteTradeMark = async(row:trademark)=>{
   try {
    await reqDeleteTradeMark(row.id)
    // 成功提示
    ElMessage({
      message:`删除${row.tmName}成功`,
      type: "success",
    });
    // 再次获取最新数据(停留再当前页)
    getTradeMarkList(currentPage.value)
   } catch (error) {
    ElMessage({
      message: '删除品牌失败',
      type: "error",
    });
   }
}


</script>

 
<style scoped>
/**上传照片的样式**/
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
